import axios from 'axios'
import md5 from 'md5'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { setToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  request => {
    if (request.url.indexOf('https://wonder-1300427053.cos.ap-guangzhou.myqcloud.com/') > -1) {
      request.timeout = 0
    }
    if (request.method === 'get') {
      if (request.url.split('?').length > 1) { request.url += ('&date=' + new Date().getTime() + '&token=' + store.state.user.token + '&functionId=' + store.state.user.functionId + '&versionChannel=2') } else { request.url += ('?date=' + new Date().getTime() + '&token=' + store.state.user.token + '&functionId=' + store.state.user.functionId + '&versionChannel=2') }
    } else if (request.method === 'post') {
      // debugger
      // request.data.language = 'en'
      if (!request.data) { request.data = {} }
      request.data.versionChannel = 2
      request.data.token = store.state.user.token
      request.data.functionId = store.state.user.functionId
      request.headers = encode(new Date().getTime(), request.data)
    }
    return request
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // 如果不是本地后台直接放回
    if (!(response.config.url.lastIndexOf('/back') < 0 || response.config.url.lastIndexOf('/merchant') < 0)) {
      return res
    }
    // 如果自定义代码不是1，则判断为错误。
    if (res.status !== 1) {
      Message({
        message: res.errorMsg,
        type: 'error',
        duration: 5 * 1000
      })
      if (res.status === 1021) {
        store.dispatch('user/resetToken')
      }
      /**
       * 0	FAIL	失败
       1	SUCCESS	成功
       1001	ACCOUNT_DISABLED	账号异常
       1002	SYSTEM_MAINTAIN	系统维护中
       1003	PARAMS_ERROR	参数错误，请核对
       1004	VERIFY_SIGN_ERROR	验证签名失败
       1005	USER_NO_EXIST	查询不到对应的用户信息
       1006	PASSWORD_ERROR	密码错误
       1007	TOKEN_OUT_TIME	token超时
       1008	PAGE_PARAMS_ERROR	分页参数异常
       1009	JURIS_PARAMS_ERROR	权限参数异常
       1010	USER_MSG_EMPTY	查询不到用户信息
       1011	JURIS_FUNCTION_PARAMS_ERROR	权限菜单ID参数异常
       1012	NO_JURIS	无权限
       1013	JURIS_FUNCTION_ROUTE_ERROR	菜单路由权限错误
       1014	SEARCH_PARAMS_ERROR	查询参数异常
       1015	MSG_EXIST	信息已经存在
       1016	MSG_EMPTY	查询不到对应信息
       1017	MSG_QUOTE	信息被引用
       1018	PART_DEL_SUCCESS	部分信息删除成功
       1019	PART_DEL_FAIL	部分信息删除失败
       1020	STATUS_ERROR	状态错误
       1021	TOKEN_ERROR	token错误
       */
      // Message.error(res.errorMsg)
      return Promise.reject(new Error(res.errorMsg || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)
// 28c258d38824454585222a8908828381
/**
 * post 请求加密
 * @param {DateTime} timestamp 时间戳
 * @param {Object} data 上传的参数
 */
function encode(timestamp, data) {
  var key = 'daylongBack@202208.'
  var platform = 'web'
  return {
    timestamp: timestamp,
    platform: platform,
    daylongBackPas: md5(timestamp + '+' + key + '+' + JSON.stringify(data) + '+' + platform)
  }
}

export default service

export const Base_API = '/daylong_back'
